import React, { useState, useEffect, useRef } from 'react';
import { Table, Button, Form, Select, DatePicker, Input, Space, Pagination, message, Modal } from 'antd';
import { DownloadOutlined, CloudUploadOutlined, StarOutlined, CopyOutlined, DeleteOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import request from '@/utils/request';
import DraggableTable from '@/components/DraggableTable';
import { restoreColumns, saveColumns, getSortState } from '@/utils/columnStorage';
import './MyFavorites.css';

const MyFavorites: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [form] = Form.useForm();
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [tableData, setTableData] = useState<any[]>([]);
  const [tableLoading, setTableLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [downloadLoading, setDownloadLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  // 排序状态
  const [sortState, setSortState] = useState({ field: null, order: null });

  // 表格容器ref和滚动高度
  const tableContainerRef = useRef(null);
  const [tableScrollY, setTableScrollY] = useState(0);

  // 计算表格滚动高度
  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      const containerHeight = tableContainerRef.current.clientHeight;
      const tableHeaderHeight = 89;
      const scrollHeight = containerHeight - tableHeaderHeight;
      setTableScrollY(scrollHeight);
      const body = tableContainerRef.current.querySelector('.ant-table-body');
      if (body) {
        body.style.height = Math.max(scrollHeight, 0) + 'px';
      }
    }
  };

  // 获取收藏列表数据
  const fetchFavoritesData = async (params: any = {}) => {
    setTableLoading(true);
    try {
      const queryParams = {
        page: current,
        page_size: pageSize,
        ...params
      };

      const response = await request.get('/Management/FavoritesList', {
        params: queryParams
      });

      if (response.status === 200) {
        const { list, count } = response.data.data;

        // 更新表格数据
        const formattedData = list.map((item: any) => ({
          key: item.id,
          id: item.id,
          fileName: item.file_name,
          path: item.file_path,
          data_type: item.data_type,
          product_id: item.product_id,
          backup: item.bk_pstate === 1 ? '已备份' : '未备份',
          collectTime: item.collection_time_start,
          collectEndTime: item.collection_time_end,
          archiveTime: item.archive_time,
          size: (item.data_size / 1024 / 1024).toFixed(2),
          task: item.task_type,
          station: item.station,
          sensor: item.dm_zhname,
          version: item.version_num,
          periodId: item.track_num_turns
        }));

        setTableData(formattedData);
        setTotal(count);
      }
    } catch (error) {
      message.error('获取收藏列表失败');
    } finally {
      setTableLoading(false);
    }
  };

  useEffect(() => {
    request.initToken();
    
    // 恢复排序状态
    const tableKey = 'my_favorites_table';
    const savedSortState = getSortState(tableKey);
    if (savedSortState) {
      setSortState(savedSortState);
    }
  }, []);

  // 监听分页变化，重新获取数据
  useEffect(() => {
    fetchFavoritesData();
  }, [current, pageSize]);


  // 计算表格滚动高度并监听窗口大小变化
  useEffect(() => {
    calculateTableScrollHeight();
    window.addEventListener('resize', calculateTableScrollHeight);
    return () => {
      window.removeEventListener('resize', calculateTableScrollHeight);
    };
  }, []);

  // 筛选表单提交
  const onFinish = (values: any) => {
    const params = {
      ...values,
      order_by: values.sort ? `${values.sort === 'desc' ? '-' : ''}${values.sortField || 'version'}` : undefined
    };
    fetchFavoritesData(params);
  };

  // 搜索过滤
  const filteredTableData = tableData.filter((item) => !searchKeyword || item.fileName.includes(searchKeyword));

  // 批量下载
  const handleBatchDownload = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要下载的数据');
      return;
    }

    setDownloadLoading(true);
    try {
      const payload = {
        is_favorites: true,
        files: selectedRowKeys.map((key) => {
          const row = tableData.find((item) => item.key === key);
          return {
            data_type: row?.data_type || '', // 从行数据中获取task作为data_type，如果没有则使用默认值
            product_id: row?.product_id || ''
          };
        })
      };

      const response = await request.post('/Management/DownloadOrder', payload);

      if (response.status === 200) {
        const { download_path } = response.data;
        message.success('请到“下载订单”中查看拟下载数据的准备情况', 5);
        setSelectedRowKeys([]);
        fetchFavoritesData();
      }
    } catch (error) {
      message.error('创建下载订单失败');
    } finally {
      setDownloadLoading(false);
    }
  };

  // 取消收藏
  const handleUnfavorite = async (record: any) => {
    try {
      const response = await request.post('/Management/FavoritesCancel', {
        file_ids: [record.id]
      });

      if (response.status === 200) {
        message.success('取消收藏成功');
        fetchFavoritesData(); // 刷新列表
      }
    } catch (error) {
      message.error('取消收藏失败');
    }
  };

  // 批量取消收藏
  const handleBatchUnfavorite = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要取消收藏的数据');
      return;
    }

    try {
      const response = await request.post('/Management/FavoritesCancel', {
        file_ids: selectedRowKeys
      });

      if (response.status === 200) {
        message.success('批量取消收藏成功');
        setSelectedRowKeys([]);
        fetchFavoritesData(); // 刷新列表
      }
    } catch (error) {
      message.error('批量取消收藏失败');
    }
  };

  // 单个文件下载
  const handleSingleDownload = async (record: any) => {
    try {
      const downloadUrl = `${request.defaults.baseURL}/Management/Download?data_type=${record.data_type}&product_id=${record.product_id}`;
      window.open(downloadUrl, '_blank');
    } catch (error) {
      message.error('下载失败');
    }
  };

  // 单个发布
  const handleSingleRelease = async (record: any) => {
    try {
      const payload = {
        release_type: 1,
        files: [
          {
            data_type: record.data_type,
            product_id: record.product_id
          }
        ]
      };

      const response = await request.post('/Management/DataRelease', payload);
      
      if (response.status === 200) {
        message.success('发布成功！');
        fetchFavoritesData();
      }
    } catch (error: any) {
      const errorMsg = error?.message || '发布失败';
      message.error(errorMsg);
    }
  };

  // 批量发布
  const handleBatchRelease = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要发布的数据');
      return;
    }

    try {
      const files = selectedRowKeys.map((key) => {
        const row = tableData.find((item) => item.key === key);
        return {
          data_type: row?.data_type || '',
          product_id: row?.product_id || ''
        };
      });

      const payload = {
        release_type: 1,
        files: files
      };

      const response = await request.post('/Management/DataRelease', payload);
      
      if (response.status === 200) {
        message.success('批量发布成功！');
        setSelectedRowKeys([]);
        fetchFavoritesData();
      }
    } catch (error: any) {
      const errorMsg = error?.message || '批量发布失败';
      message.error(errorMsg);
    }
  };

  // 全部发布
  const handleAllRelease = async () => {
    try {
      const response = await request.post('/Management/FavoritesDataReleaseAll');
      
      if (response.status === 200) {
        message.success('全部发布成功！');
        fetchFavoritesData();
      }
    } catch (error: any) {
      const errorMsg = error?.message || '全部发布失败';
      message.error(errorMsg);
    }
  };

  // 全部取消收藏
  const handleAllCancel = async () => {
    Modal.confirm({
      title: '确认取消收藏',
      content: '确定要取消所有收藏吗？此操作不可撤销。',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await request.post('/Management/FavoritesCancelAll');
          
          if (response.status === 200) {
            message.success('全部取消收藏成功');
            setSelectedRowKeys([]);
            fetchFavoritesData();
          }
        } catch (error: any) {
          const errorMsg = error?.message || '全部取消收藏失败';
          message.error(errorMsg);
        }
      }
    });
  };

  // 全部下载
  const handleAllDownload = async () => {
    try {
      const response = await request.post('/Management/FavoritesDownloadAll');
      
      if (response.status === 200) {
        message.success('全部下载成功！请到"下载订单"中查看拟下载数据的准备情况', 5);
        fetchFavoritesData();
      }
    } catch (error: any) {
      const errorMsg = error?.message || '全部下载失败';
      message.error(errorMsg);
    }
  };

  // 定义默认列配置
  const defaultColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 60,
      align: 'center' as const,
      render: (_: any, __: any, idx: number) => idx + 1 + (current - 1) * pageSize
    },
    {
      title: '文件名',
      dataIndex: 'fileName',
      key: 'fileName',
      ellipsis: { showTitle: false },
      width: 320
    },
    {
      title: '存储路径',
      dataIndex: 'path',
      key: 'path',
      ellipsis: { showTitle: false },
      width: 300
    },
    { title: '备份状态', dataIndex: 'backup', key: 'backup', width: 80 },
    { title: '采集开始时间', dataIndex: 'collectTime', key: 'collectTime', width: 140 },
    { title: '采集结束时间', dataIndex: 'collectEndTime', key: 'collectEndTime', width: 140 },
    { title: '归档时间', dataIndex: 'archiveTime', key: 'archiveTime', width: 140 },
    { title: '数据大小(MB)', dataIndex: 'size', key: 'size', width: 100 },
    { title: '任务型号', dataIndex: 'task', key: 'task', width: 60 },
    { title: '接收站', dataIndex: 'station', key: 'station', width: 80 },
    { title: '载荷', dataIndex: 'sensor', key: 'sensor', width: 80 },
    { title: '版本号', dataIndex: 'version', key: 'version', width: 60 },
    { title: '轨道圈数/探测周期编号', dataIndex: 'periodId', key: 'periodId', width: 170 },
    {
      title: '操作',
      key: 'action',
      width: 180,
      align: 'center' as const,
      fixed: 'right' as const,
      render: (_: unknown, record: any) => (
        <Space>
          <Button size="small" icon={<DownloadOutlined />} onClick={() => handleSingleDownload(record)}>
            下载
          </Button>
          <Button size="small" icon={<CloudUploadOutlined />} onClick={() => handleSingleRelease(record)}>
            发布
          </Button>
          <Button size="small" icon={<DeleteOutlined />} onClick={() => handleUnfavorite(record)}>
            取消收藏
          </Button>
        </Space>
      )
    }
  ];
  
  // 初始化列配置，从localStorage恢复
  const [columns, setColumns] = useState(() => {
    const tableKey = 'my_favorites_table';
    return restoreColumns(defaultColumns, tableKey);
  });

  // 处理列变化
  const handleColumnsChange = (newColumns: any[]) => {
    setColumns(newColumns);
  };

  // 保存列配置到localStorage
  useEffect(() => {
    if (columns.length > 0) {
      const tableKey = 'my_favorites_table';
      saveColumns(columns, tableKey, sortState);
    }
  }, [columns, sortState]);

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    columnWidth: 50,
    onChange: (keys: React.Key[]) => setSelectedRowKeys(keys)
  };

  return (
    <div className="my-favorites-container">
      <div style={{ position: 'absolute', width: '100%', display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div className="breadcrumb">
          <Button 
            type="link" 
            icon={<ArrowLeftOutlined />} 
            onClick={() => window.history.back()}
            style={{ padding: 0, marginRight: 10 }}
          >
            返回
          </Button>
          订单管理 &gt; 我的收藏
        </div>
        <div className="my-favorites-page" style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          {/* 数据表格 */}
          <div className="favorites-table-container" ref={tableContainerRef} style={{ flex: 1, overflow: 'hidden' }}>
            <DraggableTable
              columns={columns}
              onColumnsChange={handleColumnsChange}
              rowSelection={rowSelection}
              dataSource={filteredTableData}
              pagination={false}
              scroll={{ y: tableScrollY, x: 'max-content' }}
              bordered
              size="small"
              loading={tableLoading}
              rowClassName={(_, index) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
              onChange={(pagination, filters, sorter) => {
                if (sorter.field) {
                  const newSortState = {
                    field: sorter.field,
                    order: sorter.order
                  };
                  setSortState(newSortState);
                }
              }}
              footer={() => (
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Space wrap>
                    <Button type="primary" loading={downloadLoading} onClick={handleBatchDownload}>
                      批量下载
                    </Button>
                    <Button type="primary" onClick={handleAllDownload}>
                      全部下载
                    </Button>
                    <Button type="primary" onClick={handleBatchRelease}>
                      批量发布
                    </Button>
                    <Button type="primary" onClick={handleAllRelease}>
                      全部发布
                    </Button>
                    <Button type="primary" onClick={handleBatchUnfavorite}>
                      批量取消收藏
                    </Button>
                    <Button type="primary" onClick={handleAllCancel}>
                      全部取消收藏
                    </Button>
                  </Space>
                  <Pagination
                    current={current}
                    pageSize={pageSize}
                    total={total}
                    showSizeChanger={true}
                    pageSizeOptions={['10', '20', '50']}
                    onChange={(page, size) => {
                      setCurrent(page);
                      setPageSize(size!);
                    }}
                    showTotal={(total) => `共 ${total} 条`}
                    size="small"
                  />
                </div>
              )}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default MyFavorites;
